<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>websocket聊天室</title>
    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,600" rel="stylesheet">
    <link rel="stylesheet" href="css/reset.min.css">
    <link rel="stylesheet" href="css/style.css">
    <style>
        .message img {
            float: left;
            width: 40px;
            height: 40px;
            margin-right: 12px;
            border-radius: 50%;
        }

        .you {
            margin-left: 60px;
            margin-top: -39px;
        }

        .me-header {
            float: right !important;
            margin-right: 0 !important;
        }

        .me {
            margin-right: 60px;
            margin-top: -39px;
        }

        .active-chat::-webkit-scrollbar, .left::-webkit-scrollbar {
            width: 2px;
        }
        .flex{
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .ipname{
            font-size: 14px;
        }
    </style>
</head>
<body>

<div class="wrapper">
    <div class="container">
        <div class="left">
            <div class="top" style="padding: 20px 29px;height: auto;">
                <div class="" style="font: 400 13.3333px Arial;font-weight: 400;">在线人数：<span id="numbers">0</span> 人
                </div>
            </div>
            <ul class="people">
            </ul>
        </div>
        <div class="right">
            <div class="top"><span>Tips: <span class="name">Golang之websocket聊天室</span></span></div>
            <div class="chat active-chat" data-chat="person1"
                 style="height: auto;border-width: 0px;padding: 10px;height: 483px; padding: 10px;overflow-y: auto;scrollTop: 100px">
            </div>
            <div class="write">
                <a href="javascript:;" class="write-link attach"></a>
                <input type="text" id="input-value" onkeydown="confirm(event)"/>
                <a href="javascript:;" class="write-link smiley"></a>
                <a href="javascript:;" class="write-link send" onclick="send()"></a>
            </div>
        </div>
    </div>
</div>

<script src="js/jquery-2.1.1.min.js"></script>
<script src="js/index.js"></script>
<script src="js/layer/layer.js"></script>
<script>
    var userInfo = {};
    getNewUser();


    var ws = null;
    connect();
    function connect() {
        // 创建一个 websocket 连接
        ws = new WebSocket("ws://"+window.location.host+"/ws?uid="+userInfo.uname+"&img="+userInfo.headerimg);
        // websocket 创建成功事件
        ws.onopen = onopen;
        // websocket 接收到消息事件
        ws.onmessage = onmessage;
        ws.onclose = onclose;
        ws.onerror = onerror;
    }

    function onopen()
    {
        var data = "系统消息：建立连接成功";
        console.log(data);
    }

    function onmessage(e)
    {
        var data = JSON.parse(e.data);
        console.log(data)
        switch (data.type) {
            case 'handShake':
                //发送用户登录
                var user_info = {'type': 'login', 'msg': userInfo.uname, 'headerimg': userInfo.headerimg};
                sendMsg(user_info);
                break;
            case 1://系统消息
                if(data.msg == 'login'){
                    systemMessage('系统消息: ' + data.userInfo.nickname + '这家伙下线了');
                    userList(data.user_list);//刷新左侧列表
                }else if (data.msg=='logout'){
                    systemMessage('系统消息: ' + data.userInfo.nickname + ' 这家伙下线');
                    userList(data.user_list);//刷新左侧列表

                }
                console.log(data.user_list,"----user_list22")
                break;
            case 2:
                messageList(data);
                break;
            case 3:
                messageList(data);
                break;
        }
    }
    function onclose()
    {
        console.log("连接关闭，定时重连");
        connect();
    }

    // websocket 错误事件
    function onerror()
    {
        var data = "系统消息 : 出错了,请退出重试.";
        console.log(data);
    }

    function confirm(event) {
        var key_num = event.keyCode;
        if (13 == key_num) {
            send();
        } else {
            return false;
        }
    }

    //系统消息
    function systemMessage(msg) {
        var html = `<div class="conversation-start">
            <span>` + msg + `</span>
        </div>`;
        var active_chat = document.querySelector('div.active-chat');
        var oldHtml = active_chat.innerHTML;
        active_chat.innerHTML = oldHtml + html;
        active_chat.scrollTop = active_chat.scrollHeight;
    }

    //发送
    function send() {
        var msg = document.querySelector("input#input-value").value;
        var reg = new RegExp("\r\n", "g");
        msg = msg.replace(reg, "");
        sendMsg({type: 2, msg: msg});
        document.querySelector("input#input-value").value = "";
    }

    //发送消息给服务器
    function sendMsg(msg) {
        var data = JSON.stringify(msg);
        ws.send(data);
    }

    //左侧用户列表渲染
    var old_html = "";
    function userList(user) {
        var html = '';
        for (var i = 0; i < user.length; i++) {
            html += `<li class="person" data-chat="person1">
                    <img src="` + user[i].image + `" alt=""/>
                    <span class="name">` + user[i].nickname + `</span>
                   <span class="time">` + user[i].login_time + `</span>
            <div class="flex">
                <span class="preview" style="color: green;font-size: 7px;">在线</span>
                <span class="ipname" ip=`+user[i].ip+`>` + user[i].ip + `</span>
            </div>
         </li>`;
        }
        if(old_html==html){
            return
        }
        old_html = html;
        document.querySelector('ul.people').innerHTML = html;
        document.querySelector('span#numbers').innerHTML = user.length;
        getIpName();
    }

    //消息渲染
    function messageList(data) {
        if (data.userInfo.uid == userInfo.uname) {
            var html = `<div class="message">
                    <img class="me-header" src="` + data.userInfo.image + `" alt=""/>
                    <div class="bubble me">` + data.msg + `</div>
                </div>`;
        } else {
            var html = `<div class="message">
                    <img src="` + data.userInfo.image + `" alt=""/>
                    <div class="bubble you">` + data.msg + `</div>
                </div>`;
        }
        var active_chat = document.querySelector('div.active-chat');
        var oldHtml = active_chat.innerHTML;
        active_chat.innerHTML = oldHtml + html;
        active_chat.scrollTop = active_chat.scrollHeight;
    }

    /**
     * 生产一个全局唯一ID作为用户名的默认值;
     *
     * @param len
     * @param radix
     * @returns {string}
     */
    function uuid(len, radix) {
        var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
        var uuid = [], i;
        radix = radix || chars.length;

        if (len) {
            for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
        } else {
            var r;

            uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
            uuid[14] = '4';

            for (i = 0; i < 36; i++) {
                if (!uuid[i]) {
                    r = 0 | Math.random() * 16;
                    uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                }
            }
        }
        return uuid.join('');
    }


    //生成一个新用户
    function getNewUser(){
        var userKey = "webSocket|userInfo";
        var info = localStorage.getItem(userKey);
        if(info){
            info = JSON.parse(info);
            userInfo = info
        }
        //如果存在 就直接返回
        if(userInfo['uname']){
            return
        }
        userInfo['uname'] = "user" + uuid(8, 11);
        var avatar = ['a1.jpg', 'a2.jpg', 'a3.jpg', 'a4.jpg', 'a5.jpg', 'a6.jpg', 'a7.jpg', 'a8.jpg', 'a9.jpg', 'a10.jpg'];
        userInfo['headerimg'] = "img/" + avatar[Math.round(Math.random() * 10)-1];
        localStorage.setItem(userKey,JSON.stringify(userInfo));
        layer.open({
            title: '您的用户名如下',
            content: userInfo.uname,
            closeBtn: 0,
            yes: function (index, layero) {
                layer.close(index);
            }
        });
    }

    function getIpName(){
        var ips = new Array();
        $(".ipname").each(function(){
            ips.push($(this).attr("ip"));
        })
        $.getJSON("http://www.phpshe.com/index.php?mod=api&act=ipname&ips="+ips.join(",")+"&callback=?", function(json){
            $(".ipname").each(function(index){
                $(this).html(json.ipname[index]);
            })
        })
    }
</script>
</body>
</html>